package com.proj.hot.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.proj.hot.GlobalParams;
import com.proj.hot.R;
import com.proj.hot.activity.LoginActivity;
import com.proj.hot.activity.MovieDetailActivity;
import com.proj.hot.activity.PayActivity;
import com.proj.hot.adapter.MovieGalleryAdapter;
import com.proj.hot.utils.DebugUtil;
import com.proj.hot.widget.CommonGallery;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 电影
 */
public class MovieFragment extends BaseFragment {

    private final String TAG = "MovieFragment";

    private int[] imageIds = new int[]{//没有网络的时候加载默认图，暂时先不实现
            R.drawable.morentu, R.drawable.morentu, R.drawable.morentu};
    private CommonGallery commonGallery;//画廊控件
    private MovieGalleryAdapter movieGalleryAdapter;//适配器
    JSONObject jsonObject;
    JSONArray jsonArray = new JSONArray();
    public String code;//launch设置进来的code
    private List<JSONObject> jsList = new ArrayList<JSONObject>();
    private TextView movieNum;
    private int listSize;
    private int fi = 1;

    private View viewTemp;
    private RelativeLayout gallery_item_rl;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_movie, container, false);


        return rootView;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        commonGallery = (CommonGallery) getActivity().findViewById(R.id.gallery);
        movieNum = (TextView) getActivity().findViewById(R.id.moview_num);
        if (!"".equals(code) && null != code) {
            getData();
        } else {
            DebugUtil.toast(getActivity().getApplicationContext(), "服务器请求数据失败，电影code为空!");
        }
    }

    private void getData() {
        try {
            /**
             * ---------------set params------------------
             */
            JSONObject body = new JSONObject();
            body.put("code", code);
            body.put("sn", GlobalParams.SN);

            RequestParams params = new RequestParams(GlobalParams.reqHost + "featuredFirst/getDetails?"+code);
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send http------------------
             */
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        DebugUtil.i(TAG, "电影列表返回的数据=" + s);
                        JSONObject jData = new JSONObject(s);
                        jsonObject = jData.getJSONObject("respbody");
                        jsonArray = jsonObject.getJSONArray("data");
                        jsList.clear();

                        for (int i = 0; i < jsonArray.length(); i++) {
                            jsList.add(jsonArray.getJSONObject(i));
                        }

                        DebugUtil.i(TAG, "电影个数=" + jsList.size());
                        if(jsList.size() == 0){
                            movieNum.setVisibility(View.INVISIBLE);
                        }else{
                            movieNum.setVisibility(View.VISIBLE);
                            listSize = jsList.size();
                        }
                        GlobalParams.galleryListSize = jsList.size()-1;
                        setView();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {
                    DebugUtil.i(TAG, "服务器请求数据失败!:throwable=" + throwable.toString());
                    DebugUtil.toast(getActivity().getApplicationContext(), "服务器请求数据失败!");
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
            DebugUtil.i(TAG, "服务器请求数据异常!:Exception=" + e.toString());
            DebugUtil.toast(getActivity().getApplicationContext(), "服务器请求数据异常!");
        }

    }

    public void setCodeAndInitData(String code) {
        this.code = code;

    }

    private void setView() {
        movieGalleryAdapter = new MovieGalleryAdapter(getActivity().getApplicationContext(), jsList);
//        commonGallery.setSpacing(20);//item间隙
        commonGallery.setAdapter(movieGalleryAdapter);
        commonGallery.setSelection(movieGalleryAdapter.getCount() / 2);
        commonGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if (GlobalParams.IS_LOGIN) {
                    if (GlobalParams.user_paytype.equals("2")) {//包月未支付
                        Intent intent = new Intent(getActivity().getApplicationContext(), PayActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(getActivity().getApplicationContext(), MovieDetailActivity.class);
                        try {
                            //DebugUtil.i("zzzg","点击事件="+movieGalleryAdapter.getNowposition());
                            //intent.putExtra("contentid", jsList.get(movieGalleryAdapter.getNowposition()).getString("recode"));
                            //i = movieGalleryAdapter.getNowposition();
                            DebugUtil.i("zzzg", "点击事件,i=" + i + "recode=" + jsList.get(i).getString("recode"));
                            intent.putExtra("contentid", jsList.get(i).getString("recode"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
                    startActivity(intent);
                }

            }
        });

        commonGallery.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                GlobalParams.galleryFocus=fi;
            }
        });
        commonGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                // i = movieGalleryAdapter.getNowposition();
                //DebugUtil.i("zzzg", "选择事件,i=" + i);
                try {
                    movieNum.setText((i+1)+"/"+listSize);
                    GlobalParams.galleryFocus=i;
                    fi = i;
                    DebugUtil.i("zzzg", "选择事件,i=" + i + "recode=" + jsList.get(i).getString("recode"));
                   // view.startAnimation(AnimFactory.zoomInAnimation());
                    movieGalleryAdapter.setSelectItem(i);
                    movieGalleryAdapter.notifyDataSetChanged();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }

}
